package ShortCuts;
use strict;
use Data::Dumper;
use lib '/home/'.$ENV{USER}.'/djpp/core/model';
use Context;
use Response;
use Encode;
use Exporter();
our @ISA 	= qw(Exporter);
our @EXPORT = qw(&render2response &redirect2response &json2response &image2response);

sub render2response
{
	my %args = @_;
	
	my $r = $args{r};

	my $tname = $args{template} || $r->{global_vars}{base_template} || "base_template.tmpl"; 
	my $tmpl = $r->service->template->get($tname);
	
	my $context = $args{ctx} || new Context;
	
	while ( my ($k, $v) = each %{$r->{global_vars}} ){
		$context->add_ifnotexists($k, $v);
	}
	
	my $html = $tmpl->render($context);
	
	Encode::from_to($html, 'cp1251', 'utf8', $html) if $args{fromcptoutf};
	
	return new Response( 
		html => $html , 
		cookie => $args{cookie} || undef,
		type	=> $args{type} || undef,
	);			
}

sub redirect2response
{
	my ($location, $cookie) = @_;

	return new Response( 
		location 	=> $location, 
		redirect 	=> 1,
		cookie		=> $cookie || undef, 
	);
}

sub json2response
{
	my %args = @_;
	
	my $context = $args{ctx} || new Context;
	
	return new Response(
		html => $context->as_json,
	);		
}

sub image2response
{
	my %args = @_;
	
	my $type = $args{type} || 'gif'; 
	
	return new Response(
		type	=> 'image/'.$type,
		html	=> $args{data} || '',
	);	
}
1;